package com.ys.nms.module.business.service.localCompanyDevicetType;

import cn.hutool.core.collection.CollUtil;
import com.ys.nms.framework.common.util.object.BeanUtils;
import com.ys.nms.module.business.controller.admin.localCompanyDevicetType.vo.CompanyDeviceTypeListReqVO;
import com.ys.nms.module.business.controller.admin.localCompanyDevicetType.vo.CompanyDeviceTypeSaveReqVO;
import com.ys.nms.module.business.dal.dataobject.localCompanyDevicetType.CompanyDeviceTypeDO;
import com.ys.nms.module.business.dal.mysql.localCompanyDevicetType.CompanyDeviceTypeMapper;
import com.ys.nms.module.system.dal.dataobject.user.AdminUserDO;
import com.ys.nms.module.system.service.user.AdminUserService;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import jakarta.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

import static com.ys.nms.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.ys.nms.module.business.enums.ErrorCodeConstants.*;

/**
 * 设备类型 Service 实现类
 *
 * @author 超级管理员
 */
@Service
@Validated
public class CompanyDeviceTypeServiceImpl implements CompanyDeviceTypeService {

    @Resource
    private CompanyDeviceTypeMapper companyDeviceTypeMapper;

    @Resource
    private AdminUserService userService;

    @Override
    public Long createCompanyDeviceType(CompanyDeviceTypeSaveReqVO createReqVO) {
        // 校验父类型id的有效性
        validateParentCompanyDeviceType(null, createReqVO.getParentId());
        // 校验类型名称的唯一性
        validateCompanyDeviceTypeNameUnique(null, createReqVO.getParentId(), createReqVO.getName());
        setOtherData(createReqVO);
        // 插入
        CompanyDeviceTypeDO companyDeviceType = BeanUtils.toBean(createReqVO, CompanyDeviceTypeDO.class);
        companyDeviceTypeMapper.insert(companyDeviceType);

        // 返回
        return companyDeviceType.getId();
    }

    @Override
    public void updateCompanyDeviceType(CompanyDeviceTypeSaveReqVO updateReqVO) {
        // 校验存在
        validateCompanyDeviceTypeExists(updateReqVO.getId());
        // 校验父类型id的有效性
        validateParentCompanyDeviceType(updateReqVO.getId(), updateReqVO.getParentId());
        // 校验类型名称的唯一性
        validateCompanyDeviceTypeNameUnique(updateReqVO.getId(), updateReqVO.getParentId(), updateReqVO.getName());
        setOtherData(updateReqVO);
        // 更新
        CompanyDeviceTypeDO updateObj = BeanUtils.toBean(updateReqVO, CompanyDeviceTypeDO.class);
        companyDeviceTypeMapper.updateById(updateObj);
    }

    @Override
    public void deleteCompanyDeviceType(Long id) {
        // 校验存在
        validateCompanyDeviceTypeExists(id);
        // 校验是否有子设备类型
        if (companyDeviceTypeMapper.selectCountByParentId(id) > 0) {
            throw exception(COMPANY_DEVICE_TYPE_EXITS_CHILDREN);
        }
        // 删除
        companyDeviceTypeMapper.deleteById(id);
    }


    private void validateCompanyDeviceTypeExists(Long id) {
        if (companyDeviceTypeMapper.selectById(id) == null) {
            throw exception(COMPANY_DEVICE_TYPE_NOT_EXISTS);
        }
    }

    private void validateParentCompanyDeviceType(Long id, Long parentId) {
        if (parentId == null || CompanyDeviceTypeDO.PARENT_ID_ROOT.equals(parentId)) {
            return;
        }
        // 1. 不能设置自己为父设备类型
        if (Objects.equals(id, parentId)) {
            throw exception(COMPANY_DEVICE_TYPE_PARENT_ERROR);
        }
        // 2. 父设备类型不存在
        CompanyDeviceTypeDO parentCompanyDeviceType = companyDeviceTypeMapper.selectById(parentId);
        if (parentCompanyDeviceType == null) {
            throw exception(COMPANY_DEVICE_TYPE_PARENT_NOT_EXITS);
        }
        // 3. 递归校验父设备类型，如果父设备类型是自己的子设备类型，则报错，避免形成环路
        if (id == null) { // id 为空，说明新增，不需要考虑环路
            return;
        }
        for (int i = 0; i < Short.MAX_VALUE; i++) {
            // 3.1 校验环路
            parentId = parentCompanyDeviceType.getParentId();
            if (Objects.equals(id, parentId)) {
                throw exception(COMPANY_DEVICE_TYPE_PARENT_IS_CHILD);
            }
            // 3.2 继续递归下一级父设备类型
            if (parentId == null || CompanyDeviceTypeDO.PARENT_ID_ROOT.equals(parentId)) {
                break;
            }
            parentCompanyDeviceType = companyDeviceTypeMapper.selectById(parentId);
            if (parentCompanyDeviceType == null) {
                break;
            }
        }
    }

    private void validateCompanyDeviceTypeNameUnique(Long id, Long parentId, String name) {
        CompanyDeviceTypeDO companyDeviceType = companyDeviceTypeMapper.selectByParentIdAndName(parentId, name);
        if (companyDeviceType == null) {
            return;
        }
        // 如果 id 为空，说明不用比较是否为相同 id 的设备类型
        if (id == null) {
            throw exception(COMPANY_DEVICE_TYPE_NAME_DUPLICATE);
        }
        if (!Objects.equals(companyDeviceType.getId(), id)) {
            throw exception(COMPANY_DEVICE_TYPE_NAME_DUPLICATE);
        }
    }

    @Override
    public CompanyDeviceTypeDO getCompanyDeviceType(Long id) {
        return companyDeviceTypeMapper.selectById(id);
    }

    @Override
    public List<CompanyDeviceTypeDO> getCompanyDeviceTypeList(CompanyDeviceTypeListReqVO listReqVO) {
        return companyDeviceTypeMapper.selectList(listReqVO);
    }


    public void setOtherData(CompanyDeviceTypeSaveReqVO reqVO) {
        List<Long> dutyUserId = reqVO.getDutyUserId();
        List<AdminUserDO> userList = userService.getUserList(dutyUserId);
        String dutyUserName = userList.stream()
                .map(AdminUserDO::getNickname)                    // 提取 nickname
                .filter(nickname -> nickname != null && !nickname.trim().isEmpty()) // 过滤 null/空
                .collect(Collectors.joining(","));               // 用逗号拼接
        reqVO.setDutyUserName(dutyUserName);

    }

}